

package com.timi_licai.timi_licai_account.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.timi_licai.timi_licai_account.R;
import com.timi_licai.timi_licai_account.adapter.CalendarGridViewAdapter;
import com.timi_licai.timi_licai_account.utils.DateUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CalendarFragment extends Fragment implements OnItemClickListener {
    public static final String ARG_PAGE = "page";
    private Calendar calStartDate = Calendar.getInstance();// 当前显示的日历
    private int iMonthViewCurrentMonth = 0; // 当前视图月
    private int mPageNumber;

    private List<Date> alArrayList;
    private Calendar mCalendar;
    private GridView gridView;

    private CalendarGridViewAdapter calendarGridViewAdapter;

    /**
     * 调用此方法 来创建一个Fragment实例
     *
     * @param pageNumber
     * @return
     */
    public static Fragment create(int pageNumber) {
        CalendarFragment fragment = new CalendarFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, pageNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public CalendarFragment() {
    }

    private void UpdateStartDateForMonth() {
        calStartDate.set(Calendar.DATE, 1); // 设置成当月第一天
        iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);// 得到当前日历显示的月
        // 星期一是2 星期天是1 填充剩余天数
        int iDay = 0;
        int iFirstDayOfWeek = Calendar.MONDAY;
        int iStartDay = iFirstDayOfWeek;
        if (iStartDay == Calendar.MONDAY) {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
            if (iDay < 0)
                iDay = 6;
        }
        if (iStartDay == Calendar.SUNDAY) {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
            if (iDay < 0)
                iDay = 6;
        }
        calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);


        calStartDate.add(Calendar.DAY_OF_MONTH, -1);// 周日第一位


    }

    ArrayList<Date> titles;

    private List<Date> getDates() {

        UpdateStartDateForMonth();

        alArrayList = new ArrayList<Date>();

        for (int i = 1; i <= 42; i++) {
            alArrayList.add(calStartDate.getTime());
            calStartDate.add(Calendar.DAY_OF_MONTH, 1);

        }

        return alArrayList;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNumber = getArguments().getInt(ARG_PAGE);
        calStartDate = DateUtils.getSelectCalendar(mPageNumber);
        alArrayList = getDates();
        calendarGridViewAdapter = new CalendarGridViewAdapter(getActivity(),
                mCalendar, alArrayList, iMonthViewCurrentMonth);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.dialog_calendar_item, container, false);
        GridView titleGridView = (GridView) rootView
                .findViewById(R.id.gridview);
        TitleGridAdapter titleAdapter = new TitleGridAdapter(getActivity());
        initGridView(titleGridView, titleAdapter);
        GridView calendarView = (GridView) rootView
                .findViewById(R.id.calendarView);
        initGridView(calendarView, calendarGridViewAdapter);
        calendarView.setOnItemClickListener(this);
        gridView = (GridView) rootView.findViewById(R.id.calendarView);
        gridView.setOnItemClickListener(this);
        return rootView;
    }

    private void initGridView(GridView gridView, BaseAdapter adapter) {
        gridView = setGirdView(gridView);
        gridView.setAdapter(adapter);// 设置菜单Adapter
    }

    @SuppressWarnings("deprecation")
    private GridView setGirdView(GridView gridView) {
        gridView.setNumColumns(7);// 设置每行列数
        gridView.setGravity(Gravity.CENTER_VERTICAL);// 位置居中
        gridView.setVerticalSpacing(1);// 垂直间隔
        gridView.setHorizontalSpacing(1);// 水平间隔
        gridView.setBackgroundColor(Color.parseColor("#ffffff"));

        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int i = display.getWidth() / 7;
        int j = display.getWidth() - (i * 7);
        int x = j / 2;
        gridView.setPadding(x, 0, 0, 0);// 居中

        return gridView;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        for (int i = 0; i < parent.getCount(); i++) {
            if ((i % 7) == 6) {
                parent.getChildAt(i).setBackgroundColor(
                        getActivity().getResources().getColor(
                                R.color.text_6));
            } else if ((i % 7) == 0) {
                parent.getChildAt(i).setBackgroundColor(
                        getActivity().getResources().getColor(
                                R.color.text_7));
            } else {
                parent.getChildAt(i).setBackgroundColor(
                        Color.TRANSPARENT);
            }
        }
        view.setBackgroundColor(getActivity().getResources().getColor(
                R.color.selection));
        Date date = alArrayList.get(position);
        String dbDate = DateUtils.formatDateForDatabase(date);
        Intent intent = new Intent();
        intent.putExtra("dbDate", dbDate);
        getActivity().setResult(200, intent);
        getActivity().finish();
    }


    public class TitleGridAdapter extends BaseAdapter {

        int[] titles = new int[]{R.string.Sun, R.string.Mon, R.string.Tue,
                R.string.Wed, R.string.Thu, R.string.Fri, R.string.Sat};

        private Activity activity;

        // construct
        public TitleGridAdapter(Activity a) {
            activity = a;
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public Object getItem(int position) {
            return titles[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LinearLayout iv = new LinearLayout(activity);
            TextView txtDay = new TextView(activity);
            txtDay.setFocusable(false);
            txtDay.setBackgroundColor(Color.TRANSPARENT);
            iv.setOrientation(LinearLayout.VERTICAL);

            txtDay.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

            int i = (Integer) getItem(position);
            txtDay.setTextColor(Color.GRAY);
            Resources res = getResources();

            if (i == R.string.Sat) {
                // 周六
                txtDay.setBackgroundColor(res.getColor(R.color.title_text_6));
            } else if (i == R.string.Sun) {
                // 周日
                txtDay.setBackgroundColor(res.getColor(R.color.title_text_7));
            } else {
            }
            txtDay.setText((Integer) getItem(position));
            iv.addView(txtDay, lp);
            return iv;
        }
    }
}
